import { onMounted, onUnmounted, ref } from 'vue';

export function usePersistentCountdown(key: string, duration = 60) {
  const countdown = ref(0);
  const timer = ref<ReturnType<typeof setInterval>>();

  const getStorageData = () => {
    const storageData = localStorage.getItem(key);
    if (!storageData) return null;
    const { endTime } = JSON.parse(storageData);
    if (Date.now() >= endTime) {
      localStorage.removeItem(key);
      return null;
    }
    return { endTime };
  };

  const startCountdown = () => {
    if (countdown.value > 0) return;
    const endTime = Date.now() + duration * 1000;
    countdown.value = duration;
    localStorage.setItem(key, JSON.stringify({ endTime }));

    const updateCountdown = () => {
      const remaining = Math.ceil((endTime - Date.now()) / 1000);
      if (remaining <= 0) {
        countdown.value = 0;
        localStorage.removeItem(key);
        clearInterval(timer.value);
        return;
      }
      countdown.value = remaining;
    };

    timer.value = setInterval(updateCountdown, 1000);
    updateCountdown();
  };

  const stopCountdown = () => {
    if (timer.value) {
      clearInterval(timer.value);
      timer.value = undefined;
    }
    countdown.value = 0;
    localStorage.removeItem(key);
  };

  onMounted(() => {
    const data = getStorageData();
    if (data) {
      const remaining = Math.ceil((data.endTime - Date.now()) / 1000);
      if (remaining > 0) {
        countdown.value = remaining;
        const endTime = data.endTime;
        timer.value = setInterval(() => {
          const currentRemaining = Math.ceil((endTime - Date.now()) / 1000);
          if (currentRemaining <= 0) {
            countdown.value = 0;
            localStorage.removeItem(key);
            clearInterval(timer.value);
            return;
          }
          countdown.value = currentRemaining;
        }, 1000);
      }
    }
  });

  onUnmounted(() => {
    if (timer.value) {
      clearInterval(timer.value);
    }
  });

  return {
    countdown,
    startCountdown,
    stopCountdown
  };
}
